<template>
  <div class="resident-list-container">
    <el-card class="resident-card">
      <template #header>
        <div class="card-header">
          <div class="breadcrumb">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item :to="{ path: '/region/household' }">房户管理</el-breadcrumb-item>
              <el-breadcrumb-item>住户管理</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="household-info">
            <h3>{{ householdInfo }}</h3>
          </div>
          <div class="header-buttons">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增住户
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 统计卡片 -->
      <el-row :gutter="16" class="stats-row">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon primary">
                <el-icon><User /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ statistics.totalCount }}</div>
                <div class="stats-label">总住户数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon success">
                <el-icon><House /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ statistics.ownerCount }}</div>
                <div class="stats-label">户主数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon warning">
                <el-icon><UserFilled /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ statistics.familyCount }}</div>
                <div class="stats-label">家庭成员</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon info">
                <el-icon><Key /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ statistics.tenantCount }}</div>
                <div class="stats-label">租客数</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="住户姓名">
            <el-input
              v-model="searchForm.realName"
              placeholder="请输入住户姓名"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="住户身份">
            <el-select v-model="searchForm.residentType" placeholder="请选择身份" clearable style="width: 150px">
              <el-option label="户主" :value="1" />
              <el-option label="家庭成员" :value="2" />
              <el-option label="租客" :value="3" />
              <el-option label="临时居住" :value="4" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
              <el-option label="有效" :value="1" />
              <el-option label="无效" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 表格区域 -->
      <div class="table-area">
        <el-table
          v-loading="loading"
          :data="residentList"
          border
          stripe
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="realName" label="姓名" width="100" />
          <el-table-column prop="phone" label="手机号" width="130" />
          <el-table-column prop="residentType" label="住户身份" width="100">
            <template #default="{ row }">
              <el-tag :type="getResidentTypeTagType(row.residentType)" size="small">
                {{ getResidentTypeText(row.residentType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="relationship" label="关系" width="100" />
          <el-table-column prop="moveInDate" label="入住日期" width="120" />
          <el-table-column prop="applyStatus" label="申请状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getApplyStatusTagType(row.applyStatus)" size="small">
                {{ getApplyStatusText(row.applyStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getResidentStatusTagType(row.status)" size="small">
                {{ getResidentStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="280" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" text @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="success" size="small" text @click="handleView(row)">
                查看
              </el-button>
              <el-button v-if="row.applyStatus === 0" type="warning" size="small" text @click="handleApprove(row)">
                审核
              </el-button>
              <el-button type="danger" size="small" text @click="handleRemove(row)">
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-area" v-if="residentList.length > 0">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
    
    <!-- 住户表单弹窗 -->
    <ResidentForm 
      :key="currentResident?.id || currentResident?.residentId || (formVisible ? 'edit' : 'create')"
      v-model:visible="formVisible"
      :form-data="currentResident"
      :household-id="householdId"
      @success="handleFormSuccess"
    />
    
    <!-- 住户详情弹窗 -->
    <ResidentDetail 
      v-model:visible="detailVisible"
      :resident-id="detailResidentId"
    />
    
    <!-- 住户关系弹窗 -->
    <ResidentRelation 
      v-model:visible="relationVisible"
      :resident-id="relationResidentId"
      :household-id="householdId"
    />
  </div>
</template>

<script setup lang="ts">
/**
 * 住户管理页面
 * @author Wu.Liang
 * @date 2025-07-28
 */
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, User, House, UserFilled, Key } from '@element-plus/icons-vue'
import { residentApi } from '@/api/resident'
import { showMessage, getTagType } from '@/utils/message'
import ResidentForm from './ResidentForm.vue'
import ResidentDetail from './ResidentDetail.vue'
import ResidentRelation from './ResidentRelation.vue'

// 获取路由参数
const route = useRoute()
const householdId = computed(() => Number(route.query.householdId) || 0)
const householdInfo = computed(() => route.query.householdName as string || '未知房户')

// 响应式数据
const loading = ref(false)
const residentList = ref<any[]>([])
const formVisible = ref(false)
const detailVisible = ref(false)
const relationVisible = ref(false)
const currentResident = ref(null)
const detailResidentId = ref(0)
const relationResidentId = ref(0)

// 统计数据
const statistics = reactive({
  totalCount: 0,
  ownerCount: 0,
  familyCount: 0,
  tenantCount: 0
})

// 搜索表单
const searchForm = reactive({
  realName: '',
  residentType: undefined as number | undefined,
  status: undefined as number | undefined
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 住户类型映射
const residentTypeMap = {
  1: { text: '户主', type: 'success' },
  2: { text: '家庭成员', type: 'warning' },
  3: { text: '租客', type: 'info' },
  4: { text: '其他', type: 'default' }
}

// 住户状态映射
const residentStatusMap = {
  1: { text: '正常入住', type: 'success' },
  2: { text: '临时离开', type: 'warning' },
  3: { text: '已搬出', type: 'danger' },
  4: { text: '待审核', type: 'info' }
}

// 申请状态映射
const applyStatusMap = {
  0: { text: '待审核', type: 'warning' },
  1: { text: '已通过', type: 'success' },
  2: { text: '已拒绝', type: 'danger' }
}

// 获取住户类型文本
const getResidentTypeText = (type: number) => {
  return residentTypeMap[type as keyof typeof residentTypeMap]?.text || '未知'
}

// 获取住户类型标签样式
const getResidentTypeTagType = (type: number) => {
  return residentTypeMap[type as keyof typeof residentTypeMap]?.type || 'info'
}

// 获取住户状态文本
const getResidentStatusText = (status: number) => {
  return residentStatusMap[status as keyof typeof residentStatusMap]?.text || '未知'
}

// 获取住户状态标签样式
const getResidentStatusTagType = (status: number) => {
  return residentStatusMap[status as keyof typeof residentStatusMap]?.type || 'info'
}

// 获取申请状态文本
const getApplyStatusText = (status: number) => {
  return applyStatusMap[status as keyof typeof applyStatusMap]?.text || '未知'
}

// 获取申请状态标签样式
const getApplyStatusTagType = (status: number) => {
  return applyStatusMap[status as keyof typeof applyStatusMap]?.type || 'info'
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    realName: '',
    residentType: undefined,
    status: undefined
  })
  handleSearch()
}

// 加载数据
const loadData = async () => {
  if (!householdId.value) {
    showMessage({ type: 'error', message: '房户ID不能为空' })
    return
  }
  
  try {
    loading.value = true
    const params: any = {
      householdId: householdId.value,
      current: pagination.current,
      size: pagination.size
    }
    
    // 只添加有值的搜索条件
    if (searchForm.realName) {
      params.realName = searchForm.realName
    }
    if (searchForm.residentType !== undefined) {
      params.residentType = searchForm.residentType
    }
    if (searchForm.status !== undefined) {
      params.status = searchForm.status
    }
    
    const response = await residentApi.getResidentList(params)
    residentList.value = Array.isArray(response.data?.records) ? response.data.records : []
    pagination.total = response.data?.total || 0
    
    // 加载统计数据
    loadStatistics()
  } catch (error) {
    showMessage({ type: 'error', message: '加载住户列表失败' })
    residentList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 加载统计数据
const loadStatistics = async () => {
  try {
    const response = await residentApi.getResidentStatistics({ householdId: householdId.value })
    const stats = response.data
    statistics.totalCount = stats.totalCount || 0
    statistics.ownerCount = stats.ownerCount || 0
    statistics.familyCount = stats.familyCount || 0
    statistics.tenantCount = stats.tenantCount || 0
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadData()
}

// 当前页变化
const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadData()
}

// 新增住户
const handleAdd = () => {
  currentResident.value = null
  formVisible.value = true
}

// 编辑住户
const handleEdit = async (row: any) => {
  try {
    // 先获取完整的住户详情数据
    const response = await residentApi.getResidentDetail(row.residentId)
    if (response.data) {
      currentResident.value = response.data
    } else {
      // 如果获取详情失败，使用列表数据
      currentResident.value = { id: row.residentId, ...row }
    }
    // 确保子组件收到最新的formData后再打开弹窗，避免拿到上一次的ID
    await nextTick()
    formVisible.value = true
  } catch (error) {
    console.error('获取住户详情失败:', error)
    // 获取详情失败时，使用列表数据
    currentResident.value = { id: row.residentId, ...row }
    await nextTick()
    formVisible.value = true
  }
}

// 查看住户
const handleView = (row: any) => {
  detailResidentId.value = row.residentId
  detailVisible.value = true
}

// 住户关系
const handleRelation = (row: any) => {
  relationResidentId.value = row.residentId
  relationVisible.value = true
}

// 删除住户
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除住户"${row.name}"吗？删除后不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await residentApi.deleteResident(row.id)
    showMessage({ type: 'success', message: '删除成功' })
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      showMessage({ type: 'error', message: '删除失败' })
    }
  }
}

// 表单提交成功
const handleFormSuccess = () => {
  formVisible.value = false
  loadData()
}

// 页面加载时执行
onMounted(() => {
  if (householdId.value) {
    loadData()
  }
})
</script>

<style scoped>
.resident-list-container {
  padding: 20px;
}

.resident-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.breadcrumb {
  flex: 1;
}

.household-info {
  flex: 2;
  text-align: center;
}

.household-info h3 {
  margin: 0;
  color: #409eff;
}

.header-buttons {
  flex: 1;
  text-align: right;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 10px;
}

.stats-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.stats-icon.primary {
  background-color: #409eff;
}

.stats-icon.success {
  background-color: #67c23a;
}

.stats-icon.warning {
  background-color: #e6a23c;
}

.stats-icon.info {
  background-color: #909399;
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.table-area {
  margin-bottom: 20px;
}

.pagination-area {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 